package com.example.cardemo

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.cardemo.adapter.BrandlistAdapter
import com.example.cardemo.bean.BrandBean
import com.example.cardemo.bean.BrandlistBean
import com.example.cardemo.databinding.ActivityBrandlistBinding
import com.example.cardemo.utils.CarApi
import com.example.cardemo.utils.RetrofitUtils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class BrandlistActivity : AppCompatActivity() {
    val binding by lazy {
        DataBindingUtil.setContentView<ActivityBrandlistBinding>(this, R.layout.activity_brandlist)
    }
    val mDatas = mutableListOf<BrandlistBean.ResultBean>()
    val adapter: BrandlistAdapter by lazy {
        BrandlistAdapter(this, mDatas)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("BrandlistActivity", "onCreate called")
        Log.d("BrandlistActivity", "Layout loaded")
        val bean: BrandBean.ResultBean? = intent.getParcelableExtra("bean")
        if (bean != null) {
            binding.title = bean.brand_name
            binding.adapter = adapter
            bean.id?.let { loadDatas(it) }
        } else {
            Toast.makeText(this, "没有数据被接收到！", Toast.LENGTH_SHORT).show()
            finish()
        }
    }

    private fun loadDatas(id: String) {
        val api = RetrofitUtils.getApi(CarApi.base_url, CarApi::class.java)
        val call = api.getBrandlist(CarApi.key, id)
        call?.enqueue(object : Callback<BrandlistBean> {
            override fun onResponse(call: Call<BrandlistBean>, response: Response<BrandlistBean>) {
                val bean: BrandlistBean? = response.body()
                mDatas.clear()
                bean?.result?.let {
                    mDatas.addAll(it)
                    adapter.notifyDataSetChanged()
                }
            }

            override fun onFailure(call: Call<BrandlistBean>, t: Throwable) {
                Toast.makeText(this@BrandlistActivity, "获取失败，原因是： ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }
}